<!--
 * @Description: 新建、编辑账户规则
 * @Author: 0001101008/HuYuxi
 * @Date: 2021-10-11 08:50:18
 * @LastEditTime: 2021-11-11 16:31:02
 * @LastEditors: 0001100986/LiuShuai
-->
<template>
  <div class="rule-content">
    <div class="info">
      <h1 class="title">{{dialogTitle}}</h1>
      <el-form :model="form" class="form" :rules="rules" ref="ruleForm" label-width="100px">
        <!-- 规则名称 -->
        <el-form-item label="规则名称" prop="ruleName" key="ruleName">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-input v-model="form.ruleName" maxlength="100" />
          </el-col>
        </el-form-item>
        <el-divider>密码规则</el-divider>
        <!-- 密码最小限制 -->
        <el-form-item label="长度最小限制" prop="minPasswordLength" key="minPasswordLength">
          <el-input-number v-model="form.minPasswordLength" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <!-- 密码最大限制 -->
        <el-form-item label="长度最大限制" prop="maxPasswordLength" key="maxPasswordLength">
          <el-input-number v-model="form.maxPasswordLength" :min="11" :max="128"></el-input-number>
        </el-form-item>
        <!-- 密码有效期 -->
        <el-form-item label="有效期" prop="passwordValidityPeriod" key="passwordValidityPeriod">
          <el-input-number v-model="form.passwordValidityPeriod" :min="1" :max="3650"></el-input-number>
        </el-form-item>
        <!-- 强密码检测 -->
        <el-form-item label="强密码" prop="strongPasswordDetection" key="strongPasswordDetection">
          <el-switch
            v-model="form.strongPasswordDetection"
            :active-text="form.strongPasswordDetection ? '检测' : '不检测'"
          ></el-switch>
        </el-form-item>
        <!-- 首次登录修改密码 -->
        <el-form-item label="首次登录" prop="changePwdAtFirstLogin" key="changePwdAtFirstLogin">
          <el-switch
            v-model="form.changePwdAtFirstLogin"
            :active-text="form.changePwdAtFirstLogin ? '修改密码' : '不修改密码'"
          ></el-switch>
        </el-form-item>
        <el-divider>锁定规则</el-divider>
        <!-- 锁定规则 -->
        <el-form-item label="锁定规则" prop="lockRole" key="lockRole">
          <el-radio-group v-model="form.lockRole">
            <el-radio label="NEVER_LOCK">永不锁定</el-radio>
            <el-radio label="LOCK_TEMPORARILY">暂时锁定</el-radio>
            <el-radio label="LOCK_PERMANENTLY">永久锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.lockRole === 'LOCK_TEMPORARILY'">
          <!-- 允许错误次数 -->
          <el-form-item label="允许错误次数" prop="lockAfterWrongPasswords" key="lockAfterWrongPasswords">
            <el-input-number v-model="form.lockAfterWrongPasswords" :min="1" :max="10"></el-input-number>
          </el-form-item>
          <!-- 解锁时间 -->
          <el-form-item label="解锁时间" prop="unlockTime" key="unlockTime">
            <el-input-number v-model="form.unlockTime" :min="1" :max="3600"></el-input-number>
          </el-form-item>
          <!-- 自动解锁时间 -->
          <el-form-item label="自动解锁时间" prop="autoUnlockTimeIncrement" key="autoUnlockTimeIncrement">
            <el-switch
              v-model="form.autoUnlockTimeIncrement"
              :active-text="form.autoUnlockTimeIncrement ? '递增' : '不递增'"
            ></el-switch>
          </el-form-item>
        </template>
        <el-divider>账户策略</el-divider>
        <!-- 账户登录方式 -->
        <el-form-item label="登录方式" prop="accountLoginType" key="accountLoginType">
          <el-checkbox-group v-model="form.accountLoginType">
            <el-checkbox label="WEB"></el-checkbox>
            <el-checkbox label="API"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 账户长度最小限制 -->
        <el-form-item label="长度最小限制" prop="minUsernameLength" key="minUsernameLength">
          <el-input-number v-model="form.minUsernameLength" :min="3" :max="20"></el-input-number>
        </el-form-item>
        <!-- 用户闲置是否退出 -->
        <el-form-item label="闲置登出" prop="userIdleExit" key="userIdleExit">
          <el-switch v-model="form.userIdleExit" :active-text="form.userIdleExit ? '启用' : '关闭'"></el-switch>
        </el-form-item>
        <!-- 闲置退出时间 -->
        <el-form-item label="闲置时间" v-if="form.userIdleExit" prop="userIdleTime" key="userIdleTime">
          <el-input-number v-model="form.userIdleTime" :min="5" :max="60"></el-input-number>
        </el-form-item>
        <!-- 登录横幅状态 -->
        <el-form-item label="登录横幅" prop="loginBannerStatus" key="loginBannerStatus">
          <el-switch
            v-model="form.loginBannerStatus"
            :active-text="form.loginBannerStatus ? '展示' : '关闭'"
          ></el-switch>
        </el-form-item>
        <!-- 登录横幅内容 -->
        <el-form-item
          label="横幅内容"
          v-if="form.loginBannerStatus"
          prop="loginBannerDescription"
          key="loginBannerDescription"
          :rules="[
            { required: true, message: '请输入内容', trigger: 'blur'},
          ]"
        >
          <el-input
            type="textarea"
            placeholder="请输入内容"
            rows="4"
            v-model="form.loginBannerDescription"
          ></el-input>
        </el-form-item>
        <!-- 登录IP范围 -->
        <el-form-item label="登录IP范围" prop="lockAccountByIP" key="lockAccountByIP">
          <el-switch
            v-model="form.lockAccountByIP"
            :active-text="form.lockAccountByIP ? '限制' : '不限制'"
          ></el-switch>
        </el-form-item>
        <!-- 允许登录IP范围 -->
        <template v-if="form.lockAccountByIP">
          <el-form-item label="IP列表">
            <el-button icon="el-icon-plus" type="text" @click="dvEdit = true">添加</el-button>
            <el-table
              border
              :data="loginIPRange"
              class="ip-table"
              style="width: 100%"
              height="300px"
            >
              <el-table-column type="index" width="80" align="center" label="序号"></el-table-column>
              <el-table-column prop="startIPAddress" align="center" label="起始地址" width="170"></el-table-column>
              <el-table-column prop="endIPAddress" align="center" label="结束地址" width="170"></el-table-column>
              <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip></el-table-column>
              <el-table-column label="操作" align="center" width="100">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="delIp(scope)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>
        <el-form-item label-width="0">
          <el-button style="width: 90px" @click="cancel">返回</el-button>
          <el-button
            type="primary"
            style="width: 90px"
            @click="submitForm('ruleForm')"
          >{{form.id ? '保存': '创建'}}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="添加IP" :close-on-click-modal="false" width="500px" :visible.sync="dvEdit">
      <el-form
        ref="ipForm"
        :model="ipForm"
        :rules="ipRules"
        label-width="80px"
        label-position="right"
      >
        <!-- 起始地址 -->
        <el-form-item label="起始地址" prop="startIPAddress" key="startIPAddress">
          <el-input v-model.trim="ipForm.startIPAddress" />
        </el-form-item>
        <!-- 结束地址 -->
        <el-form-item label="结束地址" prop="endIPAddress" key="endIPAddress">
          <el-input v-model.trim="ipForm.endIPAddress" />
        </el-form-item>
        <!-- 描述 -->
        <el-form-item label="描述" prop="description" key="description">
          <el-input
            type="textarea"
            :rows="3"
            v-model="ipForm.description"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!--取 消  确 定-->
        <el-button @click="dvEdit = false">取消</el-button>
        <el-button type="primary" @click="addIp">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ['type', 'ruleInfo'],
  data () {
    return {
      form: {
        id: null,
        ruleName: null,
        minPasswordLength: 8,
        maxPasswordLength: 128,
        strongPasswordDetection: true,
        passwordValidityPeriod: 60,
        changePwdAtFirstLogin: false,
        lockRole: 'LOCK_TEMPORARILY',
        unlockTime: 1440,
        autoUnlockTimeIncrement: false,
        lockAfterWrongPasswords: 3,
        minUsernameLength: 3,
        accountLoginType: [],
        userIdleExit: false,
        userIdleTime: 30,
        loginBannerStatus: true,
        loginBannerDescription: '',
        lockAccountByIP: false
      },
      loginIPRange: [],
      dvEdit: false,
      ipForm: {
        startIPAddress: null,
        endIPAddress: null,
        description: null
      },
      ipRules: {
        startIPAddress: [{
          required: true,
          message: '地址不能为空',
          trigger: 'blur'
        }],
        endIPAddress: [{
          required: true,
          message: '地址不能为空',
          trigger: 'blur'
        }]
      },
      rules: {
        ruleName: [{
          required: true,
          message: '请填写规则名称',
          trigger: 'blur'
        }],
        accountLoginType: [{
          type: 'array',
          required: true,
          message: '请至少选择一个登录方式',
          trigger: 'change'
        }]
      },
      dialogTitle: '新建规则'
    };
  },
  watch: {
    type: {
      immediate: true,
      handler (val) {
        let _this = this;
        if (val === 'create') {
          _this.dialogTitle = '新建规则';
          _this.resetForm('ruleForm');
        } else {
          _this.dialogTitle = '编辑规则';
          _this.form = _this.ruleInfo;
          _this.loginIPRange = _this.ruleInfo.loginIPRange;
        }
      }
    }
  },
  methods: {
    // 移除IP
    delIp (data) {
      let _this = this;
      _this.loginIPRange.splice(data.$index, 1);
    },
    // 添加IP
    addIp () {
      let _this = this;
      _this.$refs['ipForm'].validate((valid) => {
        if (valid) {
          if (_this.ipForm.startIPAddress.substring(0, _this.ipForm.startIPAddress.lastIndexOf('.')) === _this.ipForm.endIPAddress.substring(0, _this.ipForm.endIPAddress.lastIndexOf('.'))) {
            let start = _this.ipForm.startIPAddress.substring(_this.ipForm.startIPAddress.lastIndexOf('.') + 1, _this.ipForm.startIPAddress.length);
            let end = _this.ipForm.endIPAddress.substring(_this.ipForm.endIPAddress.lastIndexOf('.') + 1, _this.ipForm.endIPAddress.length);
            if (Number(start) <= Number(end)) {
              _this.loginIPRange.push({
                startIPAddress: _this.ipForm.startIPAddress,
                endIPAddress: _this.ipForm.endIPAddress,
                description: _this.ipForm.description
              });
              _this.$refs['ipForm'].resetFields();
              _this.ipForm = {
                startIPAddress: null,
                endIPAddress: null,
                description: null
              };
              _this.dvEdit = false;
            } else {
              _this.$message.error('起始地址不能大于结束地址！');
            }
          } else {
            _this.$message.error('IP地址不在同一网段！');
          }
        } else {
          _this.$message.error('请检查必填项！');
          return false;
        }
      });
    },
    // 返回
    cancel () {
      let _this = this;
      _this.$emit('handleChange', 0);
    },
    submitForm (formName) {
      let _this = this;
      _this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 规则参数
          let params = {
            // 规则名称
            ruleName: _this.form.ruleName,
            // 密码最小长度
            minPasswordLength: _this.form.minPasswordLength,
            // 密码最大长度
            maxPasswordLength: _this.form.maxPasswordLength,
            // 强密码检测
            strongPasswordDetection: _this.form.strongPasswordDetection,
            // 密码有效期
            passwordValidityPeriod: _this.form.passwordValidityPeriod,
            // 首次登录
            changePwdAtFirstLogin: _this.form.changePwdAtFirstLogin,
            // 锁定规则
            lockRole: _this.form.lockRole,
            // 允许密码错误次数
            lockAfterWrongPasswords: _this.form.lockRole === 'LOCK_TEMPORARILY' ? _this.form.lockAfterWrongPasswords : null,
            // 解锁时间
            unlockTime: _this.form.lockRole === 'LOCK_TEMPORARILY' ? _this.form.unlockTime : null,
            // 自动解锁时间递增
            autoUnlockTimeIncrement: _this.form.lockRole === 'LOCK_TEMPORARILY' ? _this.form.autoUnlockTimeIncrement : null,
            // 登录方式
            accountLoginType: _this.form.accountLoginType,
            // 账户最小长度
            minUsernameLength: _this.form.minUsernameLength,
            // 闲置退出
            userIdleExit: _this.form.userIdleExit,
            userIdleTime: _this.form.userIdleExit ? _this.form.userIdleTime : null,
            // 登录横幅
            loginBannerStatus: _this.form.loginBannerStatus,
            loginBannerDescription: _this.form.loginBannerStatus ? _this.form.loginBannerDescription : null,
            // IP锁定
            lockAccountByIP: _this.form.lockAccountByIP,
            loginIPRange: _this.form.lockAccountByIP ? _this.loginIPRange : [],
          };
          if (_this.form.id) params.id = _this.form.id;
          const res = !_this.form.id ? await _this.$http.post({
            url: '/api/gateway/accountrule',
            data: params
          }) : await _this.$http.put({
            url: '/api/gateway/accountrule',
            data: params
          });
          if (res) {
            _this.$message({
              message: _this.form.id ? '更新成功！' : '创建成功！',
              type: 'success'
            });
            _this.resetForm(formName);
            _this.cancel();
            _this.$parent.refresh();
          }
        } else {
          this.$message.error('请检查必填项！');
          return false;
        }
      });
    },
    resetForm (formName) {
      let _this = this;
      _this.$refs[formName].resetFields();
      _this.form = {
        ruleName: null,
        minPasswordLength: 8,
        maxPasswordLength: 128,
        strongPasswordDetection: true,
        passwordValidityPeriod: 60,
        changePwdAtFirstLogin: false,
        lockRole: 'LOCK_TEMPORARILY',
        unlockTime: 1440,
        autoUnlockTimeIncrement: false,
        lockAfterWrongPasswords: 3,
        minUsernameLength: 3,
        accountLoginType: [],
        userIdleExit: false,
        userIdleTime: 30,
        loginBannerStatus: true,
        loginBannerDescription: '',
        lockAccountByIP: false
      };
      _this.loginIPRange = [];
    }
  }
};
</script>

<style lang="scss" scoped>
.rule-content {
  .header {
    background: #fff;
    padding: 30px 40px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;

    .left-wrap {
      .avatar {
        width: 110px;
        height: 110px;
        object-fit: cover;
        border-radius: 50%;
      }

      h2 {
        font-size: 30px;
        margin-top: 20px;
        font-weight: 500;
      }

      p {
        color: #9ca3ae;
        font-size: 14px;
        margin-top: 20px;
        display: none;
      }

      .task {
        margin-top: 30px;
        display: flex;
        align-items: center;

        span {
          color: #9ca3ae;
          font-size: 14px;
          margin-right: 30px;
          margin-left: 8px;
        }
      }
    }

    .right-wrap {
      display: flex;
      align-items: center;

      img {
        width: 230px;
      }
    }
  }

  .info {
    background: #fff;

    .title {
      font-size: 22px;
      font-weight: 500;
      padding: 15px 40px;
      border-bottom: 1px solid #eee;
    }

    .form {
      padding: 30px 40px;
      box-sizing: border-box;
    }
  }
}

@media only screen and (max-width: $device-ipad) {
  .ne-content {
    .header {
      padding: 20px 20px;

      .left-wrap {
        .avatar {
          width: 90px;
          height: 90px;
        }

        h2 {
          font-size: 20px;
          margin-top: 20px;
        }

        .task {
          margin-top: 15px;

          .icon {
            width: 2.8em;
            height: 2.8em;
            vertical-align: -0.15em;
          }

          span {
            font-size: 15px;
          }
        }
      }

      .right-wrap {
        display: flex;
        align-items: center;

        img {
          display: none;
        }
      }
    }

    .info {
      .title {
        font-size: 18px;
        padding: 15px 20px;
      }

      .form {
        padding: 30px 20px;
      }
    }
  }
}
.ip-table {
  ::v-deep th {
    padding: 0;
    height: 30px;
    color: #606266;
  }
  ::v-deep td {
    padding: 0;
    height: 40px;
    color: #606266;
  }
}
</style>